<template>
    <div class="sales-statistics">
        <h2>销售统计</h2>
        <canvas id="salesChart"></canvas>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { get } from "../until/request";
import { Chart, registerables } from 'chart.js';

Chart.register(...registerables);

const orders = ref([]);

onMounted(async () => {
    const response = await get('/admin/queryOrderList');
    if (response.code === 1) {
        // 过滤已支付订单
        const paidOrders = response.data.filter(order => order.isPay === '1');

        // 计算销售数据
        const salesData = calculateSalesData(paidOrders);

        // 绘制饼状图
        drawChart(salesData);
    }
});

function calculateSalesData(orders) {
    const salesMap = {};

    orders.forEach(order => {
        const productId = order.product.productId;
        if (!salesMap[productId]) {
            salesMap[productId] = {
                name: order.product.name,
                quantity: 0,
                totalPrice: 0,
                price: order.product.price
            };
        }
        salesMap[productId].quantity += order.quantity;
        salesMap[productId].totalPrice += order.totalPrice;
    });

    return Object.values(salesMap);
}

function drawChart(salesData) {
    const ctx = document.getElementById('salesChart').getContext('2d');
    new Chart(ctx, {
        type: 'pie',
        data: {
            labels: salesData.map(data => data.name),
            datasets: [{
                label: '销售总价',
                data: salesData.map(data => data.totalPrice),
                backgroundColor: [
                    '#FF6384',
                    '#36A2EB',
                    '#FFCE56',
                    '#4BC0C0',
                    '#9966FF',
                    '#FF9F40'
                ]
            }]
        },
        options: {
            responsive: true,
            plugins: {
                tooltip: {
                    callbacks: {
                        label: function (context) {
                            const data = salesData[context.dataIndex];
                            return `${data.name}: 数量 ${data.quantity}, 单价 ${data.price}, 总价 ${data.totalPrice}`;
                        }
                    }
                }
            }
        }
    });
}
</script>

<style scoped>
.sales-statistics {
    padding: 20px;
    max-width: 500px;
    margin: 0 auto;
}
</style>